package org.bingo.misc;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;

import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class MinioUtil {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private MinioClient minioClient;

    public MinioUtil(String endpoint, String accessKey, String secretKey) throws Exception {
        this.endpoint = endpoint;
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.minioClient = new MinioClient(this.endpoint, this.accessKey, this.secretKey);
    }

    public String upload(File file, String bucket) throws Exception {
        PutObjectOptions putObjectOptions = new PutObjectOptions(Files.size(file.toPath()),
                PutObjectOptions.MIN_MULTIPART_SIZE);
        minioClient.putObject(bucket,
                file.getName(),
                file.getAbsolutePath(),
                putObjectOptions);

        return String.format("%s/%s/%s", endpoint, bucket, file.getName());
    }

    public List<String> upload(List<File> fileList, String bucket) throws Exception {
        List<String> result = new ArrayList<>();
        fileList.forEach(file -> {
            try {
                result.add(upload(file, bucket));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return result;
    }

    public void delete(String bucket, String filename) {
        try {
            minioClient.removeObject(bucket, filename);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void delete(String bucket, List<String> filenames) {
        for (String filename : filenames) {
            delete(bucket, filename);
        }
    }

    public Integer getVideoDurationByM3u8(File file) {
        if (!file.exists() || !file.getName().endsWith("m3u8")) {
            return -1;
        }

        InputStream m3u8In;
        try {
            m3u8In = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
        Scanner scanner = new Scanner(m3u8In);

        Double duration = new Double(0);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.startsWith("#EXTINF:")) {
                String sliceTime = line.split(":")[1].replace(",", "");
                duration += Double.valueOf(sliceTime);
            }
        }

        scanner.close();
        try {
            m3u8In.close();
        } catch (IOException e) {
            e.printStackTrace();
            return duration.intValue();
        }
        return duration.intValue();
    }

}
